# -*- coding: utf-8 -*-
import os
import time


class Pipeline(object):
    """
    管道进程通信类 不支持windows系统
    """

    def __init__(self, base_path='/home/fate/pipe', pipe_name='pipeline', charset='utf-8'):
        if not os.path.exists(base_path):
            os.makedirs(base_path)
        self.charset = charset
        self.base_path = base_path
        self.input_pipe = os.path.join(base_path, pipe_name + '.in')
        self.output_pipe = os.path.join(base_path, pipe_name + '.out')

    def __creation_pipe(self):
        # 如果文件存在则删除
        if os.path.exists(self.input_pipe):
            os.remove(self.input_pipe)
        if os.path.exists(self.output_pipe):
            os.remove(self.output_pipe)

        # 创建管道
        os.mkfifo(self.output_pipe)
        os.mkfifo(self.input_pipe)

    def receiving_loop(self, fun):
        """ 接收端开始监听 """
        self.__creation_pipe()
        rx_in = os.open(self.input_pipe, os.O_RDONLY)
        while True:
            read_data = os.read(rx_in, 1024).decode(self.charset)
            if read_data:
                fun(read_data)
            if len(read_data) == 0:
                time.sleep(1)
                continue
        os.close(rx_in)

    def receiving_send(self, msg):
        """ 接收端发送 """
        rx_out = os.open(self.output_pipe, os.O_SYNC | os.O_CREAT | os.O_RDWR)
        os.write(rx_out, msg.encode(self.charset))
    
    def sending_loop(self, fun):
        """ 发送端开始监听 """
        send_in = os.open(self.output_pipe, os.O_RDONLY)
        while True:
            read_data = os.read(send_in, 1024).decode(self.charset)
            if len(read_data) == 0:
                time.sleep(1)
                continue
        os.close(send_in)

    def send_data(self, msg):
        """ 发送端发送数据 """
        send_out = os.open(self.input_pipe, os.O_SYNC | os.O_CREAT | os.O_RDWR)
        os.write(send_out, msg.encode(self.charset))
        os.close(send_out)